import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { toast } from 'amis';

// 全局store引用，用于清除认证状态
let globalStore: any = null;

export const setGlobalStore = (store: any) => {
  globalStore = store;
};

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: 'http://192.168.2.239:9420/prod-api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 定义响应数据类型
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data?: T;
}

// 获取token
export const getToken = (): string | null => {
  return localStorage.getItem('token');
};

// 设置token
export const setToken = (token: string): void => {
  localStorage.setItem('token', token);
};

// 移除token
export const removeToken = (): void => {
  localStorage.removeItem('token');
};

// 请求拦截器
request.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const token = getToken();
    if (token && config.headers) {
      config.headers['Authorization'] = token;
    }
    return config;
  },
  (error) => {
    console.error('Request error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    
    // 如果响应包含token，自动保存
    if (data.data?.token) {
      setToken(data.data.token);
    }
    
    return data;
  },
  (error) => {
    console.error('Response error:', error);
    
    if (error.response) {
      const { status, data } = error.response;
      
      switch (status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          removeToken();
          localStorage.removeItem('isLoggedIn');
          localStorage.removeItem('user');
          toast.error('登录已过期，请重新登录');
          
          // 如果有全局store，调用其clearAuth方法
          if (globalStore && globalStore.clearAuth) {
            globalStore.clearAuth();
          }
          
          // 强制刷新页面以确保跳转到登录页面
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          break;
        case 403:
          toast.error('没有权限访问该资源');
          break;
        case 404:
          toast.error('请求的资源不存在');
          break;
        case 500:
          toast.error('服务器内部错误');
          break;
        default:
          toast.error(data?.message || '请求失败');
      }
    } else if (error.request) {
      toast.error('网络连接失败，请检查网络');
    } else {
      toast.error('请求配置错误');
    }
    
    return Promise.reject(error);
  }
);

export default request; 